package menu.lt.pers.menu.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import menu.lt.pers.menu.Bean.NODATA;
import menu.lt.pers.menu.Bean.RecipeClassResultBean;
import menu.lt.pers.menu.Bean.ResultByClassIdBean;
import menu.lt.pers.menu.R;
import menu.lt.pers.menu.dao.ResourceDao;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class RecipeListViewAdapter extends BaseAdapter {
    private LayoutInflater inflater;
    private List<ResultByClassIdBean.ResultBean.ListBean> list;
    private HashMap<Integer,Bitmap> bitmapcache;
    private List<ResultByClassIdBean.ResultBean.ListBean.MaterialBean> material;
    private List<ResultByClassIdBean.ResultBean.ListBean.ProcessBean> process;
    private int totalRecipe;
    private int numOfOnce;
    private int classid;
    private Context context;

    public RecipeListViewAdapter(Context context, int id) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.list = new ArrayList<ResultByClassIdBean.ResultBean.ListBean>();
        this.classid = id;
        totalRecipe = 0;
        numOfOnce = 30;
        bitmapcache = new HashMap<>();
        new GetData().execute(classid,totalRecipe,numOfOnce);
    }
    @Override
    public int getCount() {
        return this.list.size();
    }

    public void updateView(){
        notifyDataSetChanged();
    }
    public void addList(){
        new GetData().execute(classid,totalRecipe,numOfOnce);
    }
    public void resetAdapter(int classid){
        this.list = new ArrayList<ResultByClassIdBean.ResultBean.ListBean>();
        totalRecipe = 0;
        new GetData().execute(classid,totalRecipe,numOfOnce);
        bitmapcache.clear();
        notifyDataSetChanged();
    }
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.classactivity_listview_resource, null);
            holder = new Holder();
            holder.imageView = convertView.findViewById(R.id.imageView);
            holder.tv_recipematerial = convertView.findViewById(R.id.tv_recipematerial);
            holder.tv_recipename = convertView.findViewById(R.id.tv_recipename);
            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }
        new GetBimap().execute(list.get(position).getPic(),position);
        if (bitmapcache.get(position)!=null){
            holder.imageView.setImageBitmap(bitmapcache.get(position));
        } else {
            holder.imageView.setImageResource(R.drawable.timg);
        }

        holder.tv_recipename.setText(list.get(position).getName());
        material = list.get(position).getMaterial();
        String materials = "";
        for(int i=0;i<material.size();i++){
            materials = materials + material.get(i).getMname()+",";
        }
        holder.tv_recipematerial.setText(materials.substring(0,materials.length()-1));
        return convertView;
    }
    public class Holder {
        private ImageView imageView;
        public TextView tv_recipename;
        public TextView tv_recipematerial;
    }

    class GetBimap extends AsyncTask {
        private int position;
        @Override
        protected Bitmap doInBackground(Object[] params) {
            position = (int) params[1];
            if (bitmapcache.get(position)==null){
                String uripath = (String) params[0];
                Log.i("getBimap.doInBackground.Thread","uri构建完毕 "+uripath);
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(5000, TimeUnit.SECONDS)
                        .readTimeout(5000,TimeUnit.SECONDS)
                        .build();
                Request request = new Request.Builder()
                        .url(uripath)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()){
                        InputStream inputStream = response.body().byteStream();//得到图片的流
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        return bitmap;
                    }else {
                        Log.i("Class.getBimap.else", list.get(position).getName()+" 获取失败 "+String.valueOf(params[0]));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o!=null && bitmapcache.get(position)==null){
                Bitmap bitmap = (Bitmap) o;
                bitmapcache.put(position,bitmap);
                notifyDataSetChanged();
            }
        }
    }
    class GetData extends AsyncTask{
        @Override
        protected ResultByClassIdBean doInBackground(Object[] params) {
            String uripath = ResourceDao.findRecipeClassUrl+"classid="+params[0]+"&"+"start="+params[1]+"&"+"num="+params[2]+"&"+
                    "appkey="+ResourceDao.appkey;
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(5000, TimeUnit.SECONDS)
                    .readTimeout(5000,TimeUnit.SECONDS)
                    .build();
            Request request = new Request.Builder()
                    .url(uripath)
                    .build();
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()){
                    String result = response.body().string();
                    Gson gson = new Gson();
                    Log.i("Adapter", "doInBackground: "+result);
                    ResultByClassIdBean resultByClassIdBean;
                    try{
                        resultByClassIdBean = gson.fromJson(result,ResultByClassIdBean.class);
                        return resultByClassIdBean;
                    } catch (com.google.gson.JsonSyntaxException e){
                        NODATA error = gson.fromJson(result,NODATA.class);
                        resultByClassIdBean = new ResultByClassIdBean();
                        resultByClassIdBean.setStatus(Integer.valueOf(error.getStatus()));
                        resultByClassIdBean.setMsg(error.getMsg());
                        return resultByClassIdBean;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            ResultByClassIdBean resultByClassIdBean = (ResultByClassIdBean) o;
            if (resultByClassIdBean!=null){
                Log.i("resultByClassIdBean!=null", "onPostExecute: "+resultByClassIdBean.getMsg());
                if (resultByClassIdBean.getStatus() == 0){
                    totalRecipe = resultByClassIdBean.getResult().getNum()+totalRecipe;
                    for (int i=0;i<resultByClassIdBean.getResult().getList().size();i++){
                        list.add(resultByClassIdBean.getResult().getList().get(i));
                    }
                    updateView();
                } else if (resultByClassIdBean.getStatus() == 205){
                    Toast.makeText(context,"没有更多数据了~~~",Toast.LENGTH_SHORT).show();
                }

            }
        }
    }

}
